import {ajax,print,base,promptBox,toast,pageTo,cacheTools} from 'nc-lightapp-front';
import requestApi, { isUploadedAttachments } from '../requestApi';
import {dataHandle, getCookie,routeChange} from '../initTemplate';
import {imageScan, imageView} from "sscrp/rppub/components/image";
import {removeDisplayScale}  from "ssccommon/utils/dataFilter";
import linkVoucherApi from '../../../../public/components/linkvoucher/linkvoucher';
import linkBudgetApi from '../../../../public/components/linkbudget/linkbudget';
import linkQueryApi from '../../../../public/components/linkquery/linkquerybills';
import {updataFormData, updatacardTableData} from 'ssccommon/utils/changePageData';
import logs from 'ssccommon/utils/logs';
import { excludeBodyKey } from '../ExpenseUtils';
import { viewModel } from 'nc-lightapp-front';
let { getGlobalStorage } = viewModel;
import attachments from 'uap/common/components/getAttachmentInfo';
const { getAttachments, getAttachmentsInfo } = attachments;
import { getSearchParams } from '../../../loanmanage/card/utils';

let debugLogs = new logs();

let pageButton = window.presetVar.pageButton;
let areaBtnAction = window.presetVar.areaBtnAction;
let statusVar = window.presetVar.status;
const { NCMessage } = base;
let jkCheck = 'false';
let ntbCheck = 'false';
let proBudgetCheck = 'false';

//fixbug YBZ-29235
function resetGlobalVar() {
    jkCheck = 'false';
    ntbCheck = 'false';
    proBudgetCheck = 'false';
}
// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);
    } else {
        sessionInfo = url;
    }


    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}

export function updateAttachment (id = 0, that) {
    getAttachments(id).then(lists => {
        that.setState({
            groupLists: lists
        }, () => {
            const filenum = that.state.groupLists;
            const fileman = that.multiLangJson['201102BCLF-0040'];
            window.presetVar.buttonTpl.button.find((items) => {
                if (items.key == 'fileManager') {
                    items.title = fileman + ' ' + filenum + ' ';
                    that.props.button.setButtonTitle(items.key, items.title);
                    return true;
                }
            });
        })
    })
}

//校验冲借款金额是否改变
function validCjk(props) {
    let cjk_vat_amount = 0
    const vat_amount = props.form.getFormItemsValue('head', 'vat_amount').value
    const cjkRows = props.cardTable.getAllRows("er_bxcontrast")
    cjkRows.forEach(row => {
        cjk_vat_amount += parseFloat(row.values.cjkbbje.value)
    })
    //相等
    if(parseFloat(vat_amount) - parseFloat(cjk_vat_amount) < 0) {
        toast({content: '冲借款金额不能大于报销金额!', color:'danger'})
        return false
    }
    return true
}

function pageButtonClick() {
    let billtype = window.presetVar.tradetype;
    let props = this.props;
    let bodys = window.presetVar.lsBodys;
    let bodyarr = [];
    let multiLang = props.MutiInit.getIntl(2011);
    let hideTable = this.state.hideTables;
    bodys.map((one)=>{
        if(hideTable.indexOf(one)<0){
            bodyarr[bodyarr.length] = one;
        }
    })
    return {
        // 查看借款详情
        ['qry_loan']: () => {
            window.loanDetailSearchData = getSearchParams(props)
            this.setState({ showLoanDetailModel: true });
        },
        [pageButton.pageSave]:async () => {
            debugLogs.timeStart('save_before');
            window.presetVar.lsBodys.forEach((body) =>{
                if(body!=='accrued_verify' && body!=='er_bxcontrast' && body!=='er_cshare_detail' && body !== 'invoice_Detail'){
                    props.cardTable.filterEmptyRows(body, ['vat_amount'], 'include');
                    props.cardTable.closeModel(body);
                }
            });

            let checkResult = props.form.isCheckNow('head') && props.cardTable.checkTableRequired();
            if (checkResult) {
                //校验附件是否必须上传
                const is_uploaded = await isUploadedAttachments.call(this, props);
                if(!is_uploaded) return

                //弹出冲借款
                let bxcontrast = props.cardTable.getAllRows("er_bxcontrast");
                if(window.presetVar&& window.presetVar.ISCONTRAST&& window.presetVar.ISCONTRAST=="Y"&&bxcontrast.length==0){
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0002'),
                        content: multiLang && multiLang.get('201102BCLF-0008'),
                        beSureBtnClick: this.cjk,
                        cancelBtnClick:this.save
                    })
                    return;
                }else{
                    let iscostshare = props.form.getFormItemsValue("head",['iscostshare'])==null?"":props.form.getFormItemsValue("head",['iscostshare'])[0].value//收款对象
                    if(iscostshare==true||iscostshare=="true"){
                        let rows = props.cardTable.getAllRows("er_cshare_detail");
                        if(rows==null||rows.length==0){
                            toast({content:multiLang && multiLang.get('201102BCLF-0019')/*"表头分摊勾选时,分摊页签不能为空!"*/,color:'warning'});
                            return ;
                        }
                    }
                    //不录入单据内容直接报错不能提交
                    let vat_amount = props.form.getFormItemsValue("head",['iscostshare'])==null?"":props.form.getFormItemsValue("head",['vat_amount'])[0].value//报销销金额
                    if(vat_amount==undefined||vat_amount==null||vat_amount==0){
                        toast({content:multiLang && multiLang.get('201102BCLF-0020')/*"报销金额不能为空!"*/,color:'warning'});
                        return;
                    }
                    let billdata =  removeDisplayScale(props.createExtCardData(props.meta.getMeta().code, "head", bodyarr));
                    requestApi.delete3status(billdata);  //过滤掉删除的行数据
                    let paramurl = getRequest1(parent.window.location.hash);
                    let paramdata = {};
                    let sense = props.getUrlParam("scene");
                    console.log(billdata);
                    paramdata.fromssc = "ssc",
                    paramdata.jkCheck = jkCheck,
                    paramdata.ntbCheck = ntbCheck,
                    paramdata.proBudgetCheck = proBudgetCheck,
                    paramdata.msg_pk_bill = "",
                    paramdata.accessorybillid = this.accessorybillid;
                    paramdata.pk_tradetype = billtype;
                    paramdata.pagecode=paramurl.p;
                    paramdata.appcode = paramurl.c;
                    let status = window.presetVar.pagestatus==''?this.props.getUrlParam("status"):window.presetVar.pagestatus;
                    if(status =="edit"){
                        paramdata.status = "edit";
                    }else{
                        paramdata.status = "save";
                    }
                    billdata.head.userjson=JSON.stringify(paramdata);
                    billdata.templetid = props.meta.getMeta().pageid;
                    console.log(billdata);
                    debugLogs.timeEnd('save_before');
                    debugLogs.timeStart('save_wate');
                    props.validateToSave(billdata,()=>{
                        requestApi.savejkbx({
                            data:billdata,
                            success:(data)=>{
                                if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                    ntbCheck = 'false';
                                }
                                debugLogs.timeEnd('save_wate');
                                debugLogs.timeStart('save_after');
                                console.log(data);

                                let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                                if(data.userjson && JSON.parse(data.userjson) && JSON.parse(data.userjson).reimmsg && JSON.parse(data.userjson).reimmsg.length>0)
                                {
                                    let billid = data.head.head.rows[0].values.pk_jkbx.value;
                                    promptBox({
                                        color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                        title: multiLang && multiLang.get('201102JCLF_C-0002'),
                                        content:JSON.parse(data.userjson).reimmsg,
                                        noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                        noCancelBtn: false,    // 是否显示取消按钮,，默认显示(false),非必输
                                        beSureBtnName:multiLang && multiLang.get('2011-0003'),
                                        cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                        beSureBtnClick: ()=>{
                                            window.presetVar.redata = 'Y';
                                            if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype,scene:sense});
                                            }else{
                                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,pagecode:paramurl.p});
                                            }
                                            routeChange.call(this, this.props)
                                        },   // 确定按钮点击调用函数,非必输
                                        cancelBtnClick: ()=>{
                                            let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                            updataFormData(props, presetVar.head.head1, newFormData);
                                            window.presetVar.reloadHead = newFormData;
                                            bodyarr.forEach((item) =>{
                                                updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                            })
                                            if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.edit,id:billid,tradetype:billtype,scene:sense});
                                            }else{
                                                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.edit,id:billid,pagecode:paramurl.p});
                                            }
                                            routeChange.call(this, this.props)                                   }
                                    })
                                }else{
                                    if(data.Alarm && data.Alarm=="Y"){
                                        promptBox({
                                            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                            title: multiLang && multiLang.get("201102BCLF-0021"),                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                                            content: data.message,             // 提示内容,非必输
                                            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
                                            beSureBtnName: multiLang && multiLang.get("201102BCLF-0017"),          // 确定按钮名称, 默认为"确定",非必输
                                            cancelBtnName: multiLang && multiLang.get("201102BCLF-0018"),         // 取消按钮名称, 默认为"取消",非必输
                                            beSureBtnClick: ()=>{
                                                if (data.AlarmType && data.AlarmType == "Project"){
                                                    proBudgetCheck = 'true';
                                                }else{
                                                    ntbCheck = 'true';
                                                }
                                                pageButtonClick.call(this)[pageButton.pageSave]();
                                            },   // 确定按钮点击调用函数,非必输
                                            // cancelBtnClick: ()=>{console.log("sdd") },  // 取消按钮点击调用函数,非必输
                                        })

                                    }else{
                                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                    let billid = data.head.head.rows[0].values.pk_jkbx.value;
                                        let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                        updataFormData(props, presetVar.head.head1, newFormData);
                                        window.presetVar.reloadHead = newFormData;
                                        // BTM 性能优化，变更页面数据更新方法
                                        bodyarr.forEach((item) =>{
                                            //冲借款保存后count会发生变化,使用set更新变化,但是需要保证返回的是全量数据
                                            if(item === 'er_bxcontrast') {
                                                props.cardTable.setTableData(item, requestApi.filterDatas(data.bodys[item]));
                                            } else {
                                                //保存后普通表体返回的是增量数据,需要updatge和合并原来数据
                                                updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                            }
                                        })
                                        if (data.AlarmType && data.AlarmType == "Project"){
                                            proBudgetCheck = 'false';
                                        }else{
                                            if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                                proBudgetCheck = 'true';
                                            }
                                            ntbCheck = 'false';
                                        }
                                        window.presetVar.redata='N';
                                        if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype,scene:sense});
                                        }else{
                                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,pagecode:paramurl.p});
                                        }
                                        routeChange.call(this, this.props)
                                    }
                                }
                                if (data.head && data.head.head && data.head.head.rows && data.head.head.rows.length) {
                                    updateAttachment(data.head.head.rows[0].values.pk_jkbx.value, this)
                                }
                                debugLogs.timeEnd('save_after');
                            },
                            error:(data)=>{
                                toast({ content: data.message, color: 'danger' });
                            }
                        });
                    },bodyarr,null);

                }

            }
        },
        [pageButton.pageClose]: async ()=>{
            let pagestatus = window.presetVar.pagestatus==''?props.getUrlParam('status'):window.presetVar.pagestatus;
            let copyid = props.getUrlParam('copyFromBillId');
            if(pagestatus == statusVar.edit || (copyid && pagestatus ==  statusVar.add)){
                //复制单据取消不校验
                const Valid = copyid && pagestatus ==  statusVar.add
                if(!Valid) {
                    //提交校验附件是否必须上传
                    const is_uploaded = await isUploadedAttachments.call(this, props)
                    if(!is_uploaded) return
                }


                let billid = props.form.getFormItemsValue("head",'pk_jkbx').value || copyid ||"";
                let appcode = (this.props.getUrlParam("appcode")==undefined||this.props.getUrlParam("appcode")=='')?this.props.getSearchParam("c"):this.props.getUrlParam("appcode");
                let pagecode =  (this.props.getUrlParam("pagecode")==undefined||this.props.getUrlParam("pagecode")=='')?this.props.getSearchParam("p"):this.props.getUrlParam("pagecode");
                let billdata = {};
                billdata.openbillid = billid;
                billdata.tradetype = window.presetVar.tradetype;
                billdata.uid = getCookie("userid");//这里以后从session中获取
                billdata.pagecode = pagecode;
                billdata.appcode = appcode;
                requestApi.viewBill({
                    data:billdata,
                    success: (data) => {
                        props.form.setAllFormValue({ [presetVar.head.head1]: data.head[presetVar.head.head1] });
                        window.presetVar.reloadHead = data.head[presetVar.head.head1];
                        //设置表体数据
                        Object.values(presetVar.body).forEach((body) => {
                            if (data.bodys[body]) {
                                debugLogs.timeStart('setTableData_' + body);
                                props.cardTable.setTableData(body, data.bodys[body]);
                                debugLogs.timeEnd('setTableData_' + body);
                            }
                        });
                        let sense = props.getUrlParam("scene");
                        if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype,scene:sense});
                        }else{

                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,pagecode:pagecode});
                        }
                        routeChange.call(this, this.props)
                    }
                });


            }else{
                window.onbeforeunload=null;
                window.top.close();

            }

        },
        [pageButton.billSubmit]: async () => {
            let sense = props.getUrlParam("scene");
            window.presetVar.lsBodys.forEach((body) =>{
                if (
                    body !== 'invoice_Detail' &&
                    body !== 'accrued_verify' &&
                    body !== 'er_bxcontrast' &&
                    body !== 'er_cshare_detail'
                ) {
                    props.cardTable.filterEmptyRows(body, ['vat_amount'], 'include');
                    props.cardTable.closeModel(body);
                }
            });
            let checkResult_sub = props.form.isCheckNow('head') && props.cardTable.checkTableRequired();
            if (checkResult_sub) {

                //提交校验附件是否必须上传
                const is_uploaded = await isUploadedAttachments.call(this, props)
                if(!is_uploaded) return

                //弹出冲借款
                let bxcontrast = props.cardTable.getAllRows("er_bxcontrast");
                let status = window.presetVar.pagestatus==''?this.props.getUrlParam("status"):window.presetVar.pagestatus;
                if((window.presetVar&&window.presetVar.ISCONTRAST&& window.presetVar.ISCONTRAST=="Y" && bxcontrast.length==0 && (status =="add" || status =="edit")) && !window.sureAssign){
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: multiLang && multiLang.get('201102BCLF-0002'),
                        content: multiLang && multiLang.get('201102BCLF-0008'),
                        beSureBtnClick: this.cjk,
                        cancelBtnClick:this.submit
                    })
                    return;
                }else{
                    let iscostshare = props.form.getFormItemsValue("head",['iscostshare'])==null?"":props.form.getFormItemsValue("head",['iscostshare'])[0].value//收款对象
                    if(iscostshare==true||iscostshare=="true"){
                        let rows = props.cardTable.getAllRows("er_cshare_detail");
                        if(rows==null||rows.length==0){
                            toast({content:multiLang && multiLang.get("201102BCLF-0019"),color:'warning'});
                            return ;
                        }
                    }
                    //不录入单据内容直接报错不能提交
                    let vat_amount = props.form.getFormItemsValue("head",['iscostshare'])==null?"":props.form.getFormItemsValue("head",['vat_amount'])[0].value//报销销金额
                    if(vat_amount==undefined||vat_amount==null||vat_amount==0){
                        toast({content:multiLang && multiLang.get("201102BCLF-0020"),color:'warning'});
                        return;
                    }
                    let send_data = {};
                    let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
                    requestApi.delete3status(billdata);
                    let paramurl = getRequest1(parent.window.location.hash);
                    let paramdata = {};
                    console.log(billdata);
                    paramdata.openbillid=!(props.getUrlParam("billid") ||props.getUrlParam("id") || this.state.billId)?"":props.getUrlParam("billid") || props.getUrlParam("id") || this.state.billId;
                    paramdata.fromssc = "ssc",
                    paramdata.jkCheck = jkCheck,
                    paramdata.ntbCheck = ntbCheck,
                    paramdata.proBudgetCheck = proBudgetCheck,
                    paramdata.msg_pk_bill = "",
                    paramdata.pk_tradetype = billtype;
                    paramdata.pagecode=paramurl.p;
                    paramdata.appcode = paramurl.c;
                    paramdata.assingUsers = window.assingUsers;
                    let appcode = (this.props.getUrlParam("appcode")==undefined||this.props.getUrlParam("appcode")=='')?this.props.getSearchParam("c"):this.props.getUrlParam("appcode");
                    let pagecode =  (this.props.getUrlParam("pagecode")==undefined||this.props.getUrlParam("pagecode")=='')?this.props.getSearchParam("p"):this.props.getUrlParam("pagecode");
                    let status = window.presetVar.pagestatus==''?this.props.getUrlParam("status"):window.presetVar.pagestatus;
                    if(status =="edit"){
                        paramdata.status = "edit";
                    } else if (status =="browse"){
                        paramdata.status = "browse";
                    }else{
                        paramdata.status = "save";
                    }
                    //如果指派点了确定  由于第一次点击保存提交实际上已经保存成功了，指派后再次提交应该走浏览提交逻辑
                    if(window.sureAssign){
                        paramdata.status = "edit";
                        paramdata.openbillid = window.assignBillId;
                    }
                    billdata.head.userjson=JSON.stringify(paramdata);
                    billdata.templetid = props.meta.getMeta().pageid;
                    billdata.accessorybillid = this.accessorybillid;
                    console.log(billdata);
                    props.validateToSave(billdata,()=>{
                        requestApi.submitBill({
                            data:billdata,
                            success:(data)=>{//设置了指派
                                ntbCheck = 'false';
                                if(data.workflow && data.billid && data.bill && (data.workflow == 'approveflow'|| data.workflow == 'workflow')){
                                    this.setState({
                                        compositedata:data,
                                        compositedisplay:true
                                    }) ;
                                    window.assignBillId = data.billid;
                                    //重新给页面赋值
                                    let newFormData = requestApi.filterDatas(data.bill.head[presetVar.head.head1]);
                                    updataFormData(props, presetVar.head.head1, newFormData);
                                    window.presetVar.reloadHead = newFormData;
                                    bodyarr.forEach((item) =>{
                                        updatacardTableData(props, item, requestApi.filterDatas(data.bill.bodys[item]));
                                    })
                                } else{
                                    this.setState({
                                        compositedisplay:false
                                    }) ;
                                    if(data.Alarm && data.Alarm=="Y"){
                                        promptBox({
                                            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                            title: multiLang && multiLang.get("201102BCLF-0021"),                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输
                                            content: data.message,             // 提示内容,非必输
                                            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
                                            beSureBtnName: multiLang && multiLang.get("201102BCLF-0017"),          // 确定按钮名称, 默认为"确定",非必输
                                            cancelBtnName: multiLang && multiLang.get("201102BCLF-0018"),         // 取消按钮名称, 默认为"取消",非必输
                                            beSureBtnClick: ()=>{
                                                if (data.AlarmType && data.AlarmType == "Project"){
                                                    proBudgetCheck = 'true';
                                                }else{
                                                    ntbCheck = 'true';
                                                }
                                                if(props.getUrlParam('status') === 'browse'){
                                                    window.sureAssign = false;
                                                }
                                                pageButtonClick.call(this)[pageButton.billSubmit]();
                                            },
                                            cancelBtnClick: () => {
                                                let billid = props.form.getFormItemsValue("head","pk_jkbx").value;
                                                if(props.getUrlParam('status') === 'browse'){
                                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype,pagecode:paramurl.p,appcode:paramurl.c});
                                                    routeChange.call(this, this.props)
                                                }else{
                                                    if(billid){
                                                        pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.edit,id:billid,pagecode:paramurl.p});
                                                        routeChange.call(this, this.props)
                                                    }else{
                                                    }
                                                }
                                                window.assingUsers = [];    //清空指派人信息
                                                window.sureAssign = false;
                                            }
                                        })

                                    }else if(data.userjson && JSON.parse(data.userjson) && JSON.parse(data.userjson).reimmsg && JSON.parse(data.userjson).reimmsg.length>0)
                                    {
                                        let billid = data.head.head.rows[0].values.pk_jkbx.value;
                                        if (data.AlarmType && data.AlarmType == "Project"){
                                            proBudgetCheck = 'false';
                                        }else{
                                            if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                                proBudgetCheck = 'true';
                                            }
                                            ntbCheck = 'false';
                                        }
                                        promptBox({
                                            color: 'warning',       // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                                            title: multiLang && multiLang.get('201102JCLF_C-0002'),
                                            content:JSON.parse(data.userjson).reimmsg,
                                            noFooter: false,  // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                                            noCancelBtn: true,    // 是否显示取消按钮,，默认显示(false),非必输
                                            beSureBtnName:multiLang && multiLang.get('2011-0003'),
                                            cancelBtnName: multiLang && multiLang.get('2011-0002') ,
                                            beSureBtnClick: ()=>{
                                                window.presetVar.redata = 'Y';
                                                //重新给页面赋值
                                                let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                                updataFormData(props, presetVar.head.head1, newFormData);
                                                window.presetVar.reloadHead = newFormData;
                                                bodyarr.forEach((item) =>{
                                                    updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                                })
                                                if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype});
                                                }else{
                                                    pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,pagecode:paramurl.p});
                                                }
                                                routeChange.call(this, this.props)
                                                window.assingUsers = [];    //清空指派人信息
                                                window.sureAssign = false;
                                            }
                                        })
                                    }else{
                                        console.log(data);
                                        // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                        // props.form.setAllFormValue({[presetVar.head.head1]: requestApi.filterDatas(data.head[presetVar.head.head1])});
                                        // window.presetVar.reloadHead = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                        let newFormData = requestApi.filterDatas(data.head[presetVar.head.head1]);
                                        updataFormData(props, presetVar.head.head1, newFormData);
                                        window.presetVar.reloadHead = newFormData;
                                        // BTM 性能优化，变更页面数据更新方法
                                        bodyarr.forEach((item) =>{
                                            // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                                            // debugLogs.timeStart('setTableData_' + item);
                                            // props.cardTable.setTableData(item, requestApi.filterDatas(data.bodys[item]));
                                            // debugLogs.timeEnd('setTableData_' + item);
                                            updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                                            // BTM 性能优化，变更页面数据更新方法
                                        })
                                        if (data.AlarmType && data.AlarmType == "Project"){
                                            proBudgetCheck = 'false';
                                        }else{
                                            if (data.proBudgetCheck && data.proBudgetCheck == "Y"){
                                                proBudgetCheck = 'true';
                                            }
                                            ntbCheck = 'false';
                                        }
                                        let billid = data.head.head.rows[0].values.pk_jkbx.value;
                                        // window.open(window.location.origin+'/erm/expenseaccount/expenseaccount/card#status=browse&openbillid='+billid+'&tradetype=2641');
                                        // location.hash = `#status=${statusVar.browse}&billid=${billid}&tradetype=${billtype}`;
                                        window.presetVar.redata='N';
                                        if(sense && (sense=="approve" || sense=="zycl" || sense=="approvesce")){
                                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,tradetype:billtype,sence:sense});
                                        }else{
                                            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{isfromSsc:true,status:statusVar.browse,id:billid,pagecode});
                                        }
                                        routeChange.call(this, this.props)
                                        props.button.setButtonsVisible({
                                            [pageButton.pageSave] : false,
                                            [pageButton.pageEdit] : false,
                                            [pageButton.billSubmit] : false,
                                            [pageButton.billRecall] : true,
                                            [pageButton.pageDel] : false,
                                            [pageButton.billInvalid] : false,
                                            [pageButton.pageClose]: false
                                        });
                                        window.assingUsers = [];    //清空指派人信息
                                        window.sureAssign = false;
                                        // //处理按钮相关状态
                                        // dataHandle(data.head.head,props);
                                        // props.form.setFormStatus('head', 'browse');
                                        // props.billBodys && props.billBodys.forEach((body)=>{
                                        //     props.editTable.setStatus(body, 'browse');
                                        // });

                                    }
                                }
                                data.head && updateAttachment(data.head.head.rows[0].values.pk_jkbx.value, this)
                            },
                            error:(data)=>{
                                toast({ content: data.message, color: 'danger' });
                            }
                        });
                    },bodyarr,null);

                }


                // props.form.setFormStatus('head', 'browse');
                // props.billBodys.forEach((body)=>{
                //     props.editTable.setStatus(body, 'browse');
                // });

            }
        },
        [pageButton.pageCopy]:()=>{//单据复制
            // location.hash = `#status=${presetVar.status.add}&copyFromBillId=${props.getUrlParam('billid')}&tradetype=${window.presetVar.tradetype}&appcode=${window.presetVar.appcode}&pagecode=${window.presetVar.pagecode}`;
            resetGlobalVar()
            let rows = props.cardTable.getAllRows('arap_bxbusitem');
            let ispull = "N";

            if(props.form.getFormItemsValue("head","pk_item").value){
                ispull = 'Y';
            }
            if (ispull!=='Y') {
                for(let i=0;i<rows.length;i++){
                    let row = rows[i];
                    if(row.values['pk_mtapp_detail']!=null
                        &&row.values['pk_mtapp_detail']!=undefined
                        &&row.values['pk_mtapp_detail'].value!=null
                        &&row.values['pk_mtapp_detail'].value!=''){
                        ispull = 'Y';
                        break;
                    }
                }
            }
            if(ispull==='Y'){
                toast({content:multiLang && multiLang.get("201102BCLF-0022"),color:'warning'});
                return;
            }else{
                pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{
                    status:presetVar.status.add,
                    copyFromBillId:props.getUrlParam('billid')||props.getUrlParam('id'),
                    tradetype:window.presetVar.tradetype
                    // appcode:window.presetVar.appcode,
                    // pagecode:window.presetVar.pagecode
                });
                routeChange.call(this, this.props)
                window.assingUsers=[];
                 //复制出来的单据要先清空附件产生的单据pk
                this.accessorybillid = '';
                this.setState({ billId: ''});
                let multiLang = this.props.MutiInit.getIntl(2011);
                let button = props.button.getButtons();
                button.forEach((items) => {
                    if (items.key == 'fileManager') {
                        items.title = items.title.match( /[\u4e00-\u9fa5]/g).join("") + ' ' + 0 + ' ';
                        this.props.button.setButtonTitle(items.key, items.title);
                    }
                });
                // this.props.button.setButtonTitle('fileManager', multiLang&&multiLang.get('201102BCLF-0040')/**'附件'**/ + ' ' + 0 + ' ');
            }

        },

        [pageButton.pageDel]:()=>{//删除单据

            let param = {};
            param.openbillid=this.props.getUrlParam('billid')||this.props.getUrlParam('id');
            requestApi.deleteBill({
                data: param,
                success: (data) => {
                    if(data.success){
                        window.onbeforeunload=null;
                        window.top.close();
                    }
                }
            });
        },


        [pageButton.billInvalid]:()=>{//单据作废
            // props.modal.show(presetVar.pageButton.billInvalid);
            let param = {};
            param.openbillid=this.props.getUrlParam("id")||this.props.getUrlParam("billid");
            param.tradetype=window.presetVar.tradetype;
            param.pagecode=this.props.getSearchParam("p");
            requestApi.billInvalid({
                data: param,
                success: (data) => {
                    if (data.success) {
                        dataHandle(data.data.head.head,this.props,this.props.getUrlParam("status"));
                        toast({content:multiLang && multiLang.get("201102BCLF-0054"),color:'success'});
                        return ;
                    }
                }
            });
        },


        [pageButton.pagePrint]:()=>{//打印单据
            let vdata = {};
            vdata.billId = props.getUrlParam('billid') || props.getUrlParam('id');
            vdata.billType = '2641';
            ajax({
                url: '/nccloud/erm/expenseaccount/ErmPrintValidaAction.do',
                data: vdata,
                success: (data) => {
                    if (!data.data.canPrint){
                        NCMessage.create({content:data.data.errMesg, color: 'error', position: 'bottom'});
                    }else {
                        print(
                            'pdf',  //支持两类: 'html'为模板打印, 'pdf'为pdf打印
                            '/nccloud/erm/expenseaccount/ErmJkbxPrintAction.do', //后台服务url
                            {
                                billtype:billtype,  //单据类型
                                funcode:(props.getUrlParam("appcode")==undefined||props.getUrlParam("appcode")=='')?props.getSearchParam("c"):props.getUrlParam("appcode"),      //功能节点编码，即模板编码
                                nodekey:'2641_IWEB',     //模板节点标识
                                oids:[props.getUrlParam('id')||props.getUrlParam('billid')]    // 功能节点的数据主键   oids含有多个元素(['1001A41000000000A9LR','1001A410000000009JDD'])时为批量打印,
                            }
                        )
                    }
                }
            })
        },

        [pageButton.imageUpload]:()=>{//影像扫描

            let openbillid = props.getUrlParam('id') || props.getUrlParam('billid');
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);

            var billInfoMap = {};

            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.djlxbm.value;
            billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;

            //影像所需 FieldMap
            billInfoMap.BillType = billdata.head.head.rows[0].values.djlxbm.value;
            billInfoMap.BillDate = billdata.head.head.rows[0].values.djrq.value;
            billInfoMap.Busi_Serial_No = billdata.head.head.rows[0].values.pk_jkbx.value;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.OrgNo = billdata.head.head.rows[0].values.pk_org.value;
            billInfoMap.BillCode = billdata.head.head.rows[0].values.djbh.value;
            billInfoMap.OrgName = billdata.head.head.rows[0].values.pk_org.display;
            billInfoMap.Cash = billdata.head.head.rows[0].values.vat_amount.value;

            imageScan(billInfoMap, 'iweb');

        },


        [pageButton.imageShow]:()=>{//影像查看

            let openbillid = props.getUrlParam('id') || props.getUrlParam('billid');
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
            var billInfoMap = {};

            //基础字段 单据pk,单据类型，交易类型，单据的组织
            billInfoMap.pk_billid = openbillid;
            billInfoMap.pk_billtype = billdata.head.head.rows[0].values.pk_billtype.value;
            billInfoMap.pk_tradetype = billdata.head.head.rows[0].values.djlxbm.value;
            billInfoMap.pk_org = billdata.head.head.rows[0].values.pk_org.value;
            imageView(billInfoMap,  'iweb');
        },

        [pageButton.invoiceView]: () => {
            let props = this.props;
            const billId = props.form.getFormItemsValue("head","pk_jkbx").value;
            const billtype  = props.form.getFormItemsValue("head","djbh").value;
            const pk_org = props.form.getFormItemsValue("head","pk_org").value;
            const tradetype = window.presetVar.tradetype;
            const crypto = window.crypto || window.msCrypto;
            const array = new Uint32Array(1);
            const viewRandom = crypto.getRandomValues(array)[0];
            this.setState({sscivmInvoiceData: { billId, billtype , pk_org, tradetype, viewRandom }});
        },

        [pageButton.linkQueryFysq]: () => {
            let billId = this.state.billId || props.getUrlParam('billid') || props.getUrlParam("id");
            ajax({
                url: '/nccloud/erm/loanmanage/LinkFysqAction.do',
                data: {
                    tradetype: window.presetVar.tradetype,//交易类型
                    openBillId: billId//单据主键ok
                },
                success: result => {
                    if (result.data && result.data.jkdBillModel) {
                        this.setState({
                            linkData: result,
                            showLinkQueryFysqModel: true,
                            billId: billId
                        })
                    } else if (result.data && result.data.sqdList) {
                        result.data.sqdList.forEach((item) => {
                            linkQueryApi.link({
                                data : {
                                    openbillid : item.pk,
                                    tradetype : item.tradetype,
                                    props : this.props
                                }
                            });
                        })
                    } else if (result.data && result.data.tradetype && result.data.pk) {
                        linkQueryApi.link({
                            data : {
                                openbillid : result.data.pk,
                                tradetype : result.data.tradetype,
                                props : this.props
                            }
                        });
                    } else {
                        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
                        toast({ content: multiLang && multiLang.get('201102JCLF_C-0001'), color: 'warning' });
                    }
                }
            });
        },

        [pageButton.linkQueryFyyt]: () => {
            let billId = this.state.billId || props.getUrlParam('billid') || props.getUrlParam("id");
            ajax({
                url: '/nccloud/erm/expenseaccount/expenseaccountLinkQueryAction.do',
                data: {
                    queryType: 'fyyt',
                    tradetype: window.presetVar.tradetype,//交易类型
                    openBillId: billId//单据主键ok
                },
                success: result => {
                    if(result.data) {
                        this.setState({
                            linkData: result,
                            showLinkQueryFyytModel: true,
                            billId: billId,
                        })
                    }else{
                        let multiLang = this.props.MutiInit.getIntl(2011); //"您联查的费用预提单没有数据
                        toast({ content: multiLang && multiLang.get('201102JCLF_C-0006'), color: 'warning' });
                    }
                }
            });
        },

        [pageButton.linkQueryJkbx]: () => {
            let billId = this.state.billId || props.getUrlParam('billid') || props.getUrlParam("id");
            ajax({
                url: '/nccloud/erm/expenseaccount/expenseaccountLinkQueryAction.do',
                data: {
                    queryType: 'jkbx',
                    tradetype: window.presetVar.tradetype,//交易类型
                    openBillId: billId//单据主键ok
                },
                success: result => {
                    if(result.data) {
                        this.setState({
                            linkData: result,
                            showLinkQueryJkbxModel: true,
                            billId: billId
                        })
                    }else{
                        let multiLang = this.props.MutiInit.getIntl(2011); //"您联查的借款单没有数据
                        toast({ content: multiLang && multiLang.get('201102JCLF_C-0007'), color: 'warning' });
                    }
                }
            });
        },

        [pageButton.pageCjk]:()=>{
            let props = this.props;
            if(this.state.showCJKModal){
                this.setState({ showCJKModal: false });

            }
            else {
                let amount = props.form.getFormItemsValue("head","total").value;
                if(parseFloat(amount) ==0){
                    toast({color:"danger",content:multiLang && multiLang.get("201102BCLF-0024")});
                }else{
                    window.bxcontrastGrid = props.cardTable.getAllRows("er_bxcontrast");
                    let param = {};
                    param.tradetype = window.presetVar.tradetype;
                    param.pk_jkbx = props.form.getFormItemsValue("head","pk_jkbx").value;
                    param.jkbxr = props.form.getFormItemsValue("head","jkbxr").value;
                    param.receiver = props.form.getFormItemsValue("head","receiver").value;
                    param.bzbm = props.form.getFormItemsValue("head","bzbm").value;
                    param.djrq = props.form.getFormItemsValue("head","djrq").value;
                    param.dwbm = props.form.getFormItemsValue("head","dwbm").value;
                    if(props.form.getFormItemsValue("head","pk_item").value){
                        param.pk_item = props.form.getFormItemsValue("head","pk_item").value;
                    }else{
                        param.pk_item = "";
                    }
                    let bodyBZ = [];
                    let pk_items = [];
                    let bzjeMap = new Map();
                    let showData = props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
                    requestApi.delete3status(showData) //表体删除行过滤
                    Object.keys(showData.bodys).forEach((item,index) =>{
                        // if (item == "arap_bxbusitem" || item == "bzitem" || item == "other" || item == "zsitem") {
                            if(excludeBodyKey(item)) {
                            showData.bodys[item].rows.forEach((row) =>{
                                if (row.values.bzbm && row.values.bzbm.value) {
                                    bodyBZ.push(row.values.bzbm);
                                    var amount = !row.values["vat_amount"].value?"0":row.values["vat_amount"].value;//取含税金额
                                    if(bzjeMap.has(row.values.bzbm.value)){
                                        var oldAmount = parseFloat(bzjeMap.get(row.values.bzbm.value));
                                        bzjeMap.delete(row.values.bzbm.value);
                                        bzjeMap.set(row.values.bzbm.value,oldAmount+parseFloat(amount));
                                    }else{
                                        bzjeMap.set(row.values.bzbm.value,amount);
                                    }
                                }
                                if (row.values.pk_item && row.values.pk_item.value){
                                    pk_items.push(row.values.pk_item.value);
                                }
                            });
                        }
                    });
                    param.bzbms = bodyBZ;
                    param.pk_items = pk_items;
                    param.total = showData.head.head.rows[0].values.total.value;
                    window.cjkdata = param;
                    window.bxjeMap = bzjeMap;
                    this.setState({ showCJKModal: true });
                }

            }
        },

        [pageButton.pageFyyt]:()=>{
            let props = this.props;
            if(this.state.showFyytModal){
                this.setState({ showFyytModal: false });
            }
            else {
                let amount = props.form.getFormItemsValue("head","total").value;
                if(parseFloat(amount) ==0){
                    toast({color:"danger",content:multiLang && multiLang.get("201102BCLF-0023")});
                   // NCMessage.create({content: multiLang && multiLang.get("201102BCLF-0023"), color: 'error', position: 'bottom'});
                }else if(props.form.getFormItemsValue("head","pk_item").value){
                    toast({color:"danger",content:multiLang && multiLang.get("201102BCLF-0046")});
                }else if(props.form.getFormItemsValue("head","iscostshare").value == true){//分摊
                    toast({color:"danger",content:multiLang && multiLang.get("201102BCLF-0047")});
                }else if(props.form.getFormItemsValue("head","isexpamt").value == true){//待摊
                    toast({color:"danger",content:multiLang && multiLang.get("201102BCLF-0048")});
                }else{
                    window.accruedverifyGrid = props.cardTable.getAllRows("accrued_verify");
                    var param = {};
                    param.pk_jkbxr = props.form.getFormItemsValue("head","jkbxr").value;
                    param.pk_bxd = props.form.getFormItemsValue("head","pk_jkbx").value;
                    param.bzbm = props.form.getFormItemsValue("head","bzbm").value;
                    param.pk_org = props.form.getFormItemsValue("head","pk_org").value;
                    param.amount = props.form.getFormItemsValue("head","total").value;
                    window.bxdata = param;
                    this.setState({ showFyytModal: true });
                }

            }

        },
        [pageButton.invoiceDzfp]: () => {
            let vdata = {};
            vdata.billId = props.getUrlParam('billid') || props.getUrlParam('id');
            vdata.billType = '2641';
            ajax({
                url: '/nccloud/erm/expenseaccount/ErmDzfpAction.do',
                data: vdata,
                success: (data) => {
                    if (!data.data.canOpenDzfp){
                        // NCMessage.create({content:data.data.errMesg, color: 'error', position: 'bottom'});
                        toast({content:data.data.errMesg,color:'warning'});
                    }else {
                        let props = this.props;
                        const billId = props.form.getFormItemsValue("head","pk_jkbx").value;
                        const billtype = props.form.getFormItemsValue("head","djbh").value;
                        const pk_org = props.form.getFormItemsValue("head","pk_org").value;
                        const tradetype = window.presetVar.tradetype;
                        const crypto = window.crypto || window.msCrypto;
                        const array = new Uint32Array(1);
                        const random = crypto.getRandomValues(array)[0];

                        this.setState({sscivmInvoiceData: { billId, billtype, pk_org, tradetype, random }});
                    }
                }
            })

        },


        [pageButton.fileManager]: () => {
            let props = this.props;
            let billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || "";
            let billtype = window.presetVar.tradetype || "";
            if (billId == "" && !this.state.showUploader){
                //去后台生成单据主键
                requestApi.generatBillId({
                    data: {billtype: billtype},
                    success:(data)=>{
                        console.log(data);
                        let accessorypkfildname = data["pkfieldName"];
                        billId = data[accessorypkfildname];
                        this.setState({
                            billId: billId ,
                            showUploader: !this.state.showUploader
                        });
                        this.accessorybillid = billId;
                    },
                    error:(data)=>{
                        toast({ content: data.message, color: 'danger' });
                    }
                });
            } else {
                this.setState({
                    billId: billId ,
                    showUploader: !this.state.showUploader
                });
            }
        },
        [pageButton.pageEdit]: ()=>{
            proBudgetCheck = 'false';
            ntbCheck = 'false';
            let props = this.props;
            let meta = props.meta.getMeta();

            let scene = props.getUrlParam('scene');
            //获取单据编号
            let djbh = props.form.getFormItemsValue("head",['djbh'])[0].value;
            let canEdit = true;
            let isMaker = true;
            //来源于审批中心
            if(scene == 'approve'  || scene == 'approvesce' ){
                isMaker = false;
                //判断单据是否是当前用户待审批
                ajax({
                    url: '/nccloud/riart/message/list.do',
                    async: false,
                    data: {
                        billno: djbh,
                        isread:'N'
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang && multiLang.get("201102BCLF-0026"),color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }
            //来源于我的作业
            if(scene == 'zycl'){
                isMaker = false;
                //判断单据是否是当前用户待处理
                ajax({
                    url: '/nccloud/ssctp/sscbd/SSCTaskHandlePendingNumAction.do',
                    async: false,
                    data: {
                        billno: djbh
                    },
                    success: result => {
                        if(result.data) {
                            if(result.data.total < 1){
                                toast({content:multiLang && multiLang.get("201102BCLF-0027"),color:'warning'});
                                canEdit =false;
                            }
                        }
                    }
                });
            }
            //特殊数据权限校验
            ajax({
                url: '/nccloud/erm/pub/ErmBillEditAction.do',
                async: false,
                data: {
                    'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                    'billid': props.form.getFormItemsValue("head",['pk_jkbx'])[0].value,
                    'billType':props.form.getFormItemsValue("head",['djlxbm'])[0].value
                },
                success: result => {

                },
                error: (data) => {
                    canEdit = false;
                    toast({ content: data.message, color: 'danger' });
                }
            });

            if(!canEdit){
                return;
            }

            if(isMaker){
                //驳回不重走流程单据，设置不可编辑字段
                requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue("head",['pk_jkbx'])[0].value,
                        'billType':props.form.getFormItemsValue("head",['djlxbm'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let arap_bxbusitemobj = [];
                            let otherobj = [];
                            let zsitemobj = [];
                            let bzitemobj = [];
                            let er_cshare_detailobj = [];
                            let er_bxcontrastobj = [];
                            let accrued_verifyobj = [];

                            data.forEach((item) => {
                                if(item.indexOf('er_busitem.')>-1){
                                    arap_bxbusitemobj.push(item.split('.')[1]);
                                    otherobj.push(item.split('.')[1]);
                                    zsitemobj.push(item.split('.')[1]);
                                    bzitemobj.push(item.split('.')[1]);
                                }else if(item.indexOf('er_cshare_detail.')>-1){
                                    er_cshare_detailobj.push(item.split('.')[1]);
                                }else if(item.indexOf('er_bxcontrast.')>-1){
                                    er_bxcontrastobj.push(item.split('.')[1]);
                                }else if(item.indexOf('accrued_verify.')>-1){
                                    accrued_verifyobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = true;
                                }
                            })
                            props.form.setFormItemsDisabled('head',formobj)
                            props.cardTable.setColEditableByKey('arap_bxbusitem',arap_bxbusitemobj)
                            props.cardTable.setColEditableByKey('other',otherobj)
                            props.cardTable.setColEditableByKey('zsitem',zsitemobj)
                            props.cardTable.setColEditableByKey('bzitem',bzitemobj)
                            props.cardTable.setColEditableByKey('er_cshare_detail',er_cshare_detailobj)
                            props.cardTable.setColEditableByKey('er_bxcontrast',er_bxcontrastobj)
                            props.cardTable.setColEditableByKey('accrued_verify',accrued_verifyobj)
                        }
                    }
                })
            }else{
                //除制单人环节外的可编辑属性

                requestApi.getUnEditAttributes({
                    data: {
                        'pk_org': props.form.getFormItemsValue("head",['pk_org'])[0].value,
                        'billid': props.form.getFormItemsValue("head",['pk_jkbx'])[0].value,
                        'billType':props.form.getFormItemsValue("head",['djlxbm'])[0].value
                    },
                    success: (data) => {
                        if(!(data==undefined || data.length == 0)){
                            let formobj = {};
                            let arap_bxbusitemobj = [];
                            let otherobj = [];
                            let zsitemobj = [];
                            let bzitemobj = [];
                            let er_cshare_detailobj = [];
                            let er_bxcontrastobj = [];
                            let accrued_verifyobj = [];
                            let bodys = Object.values(window.presetVar.body);

                            data.forEach((item) => {
                                if(item.indexOf('er_busitem.')>-1){
                                    arap_bxbusitemobj.push(item.split('.')[1]);
                                    otherobj.push(item.split('.')[1]);
                                    zsitemobj.push(item.split('.')[1]);
                                    bzitemobj.push(item.split('.')[1]);
                                }else if(item.indexOf('er_cshare_detail.')>-1){
                                    er_cshare_detailobj.push(item.split('.')[1]);
                                }else if(item.indexOf('er_bxcontrast.')>-1){
                                    er_bxcontrastobj.push(item.split('.')[1]);
                                }else if(item.indexOf('accrued_verify.')>-1){
                                    accrued_verifyobj.push(item.split('.')[1]);
                                }else{
                                    formobj[item] = false;
                                }
                            })
                            props.form.setFormItemsDisabled('head',formobj)
                            // props.cardTable.setColEditableByKey('arap_bxbusitem',arap_bxbusitemobj,false)
                            // props.cardTable.setColEditableByKey('other',otherobj,false)
                            // props.cardTable.setColEditableByKey('zsitem',zsitemobj,false)
                            // props.cardTable.setColEditableByKey('bzitem',bzitemobj,false)
                            props.cardTable.setColEditableByKey('er_cshare_detail',er_cshare_detailobj,false)
                            props.cardTable.setColEditableByKey('er_bxcontrast',er_bxcontrastobj,false)
                            props.cardTable.setColEditableByKey('accrued_verify',accrued_verifyobj,false)

                            if (bodys) {
                                bodys.forEach((one)=>{
                                    if (excludeBodyKey(one)){
                                        props.cardTable.setColEditableByKey(one,arap_bxbusitemobj,false)
                                    }
                                 })
                            }
                        }
                    }
                })
            }

            // BTM 金额字段不需要显示默认值
            props.meta.setMeta(meta);
            // location.hash = `#status=${statusVar.edit}&billid=${this.props.getUrlParam('id')||props.getUrlParam('billid')}&tradetype=${window.presetVar.tradetype}`;
            window.presetVar.redata = 'N';
            pageTo.specialLinkTo('/erm/expenseaccount/expenseaccount/card/index.html',{
                status:statusVar.edit,
                id:props.getUrlParam('id')||props.getUrlParam('billid'),
                scene:props.getUrlParam('scene'),
                tradetype:window.presetVar.tradetype

            });
            routeChange.call(this, this.props)
            // props.button.setButtonsVisible({
            //     [pageButton.pageSave]: true,
            //     [pageButton.pageEdit]: false
            // });
            // props.billBodys.forEach((body)=>{
            //     props.editTable.setStatus(body, 'edit');
            // });
        },[pageButton.billRecall]: () => {//收回
            let param = {};
            param.openbillid=this.props.getUrlParam('id')||this.props.getUrlParam('billid');
            param.pagecode=this.props.getSearchParam("p");
            requestApi.billRecall({
                data: param,
                success: (data) => {
                    let billid = data.head.head.rows[0].values.pk_jkbx.value;
                    // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                    // props.form.setAllFormValue({[presetVar.head.head1]: requestApi.filterDatas(data.head[presetVar.head.head1])});
                    updataFormData(props, presetVar.head.head1, requestApi.filterDatas(data.head[presetVar.head.head1]));
                    // BTM 性能优化，变更页面数据更新方法
                    bodyarr.forEach((item) =>{
                        // TOP 性能优化，变更页面数据更新方法 chengwbc MOD
                        // debugLogs.timeStart('setTableData_' + item);
                        // props.cardTable.setTableData(item, requestApi.filterDatas(data.bodys[item]));
                        // debugLogs.timeEnd('setTableData_' + item);
                        updatacardTableData(props, item, requestApi.filterDatas(data.bodys[item]));
                        // BTM 性能优化，变更页面数据更新方法
                    })
                    // location.hash = `#status=${statusVar.browse}&id=${billid}&tradetype=${window.presetVar.tradetype}&flow=recall`;
                    window.presetVar.redata = 'N';
                    // 更新head,避免收回后页面按钮状态错误
                    window.presetVar.reloadHead = data.head.head;

                    dataHandle.call(this, data.head.head,this.props,this.props.getUrlParam("status"));
                    // props.button.setButtonsVisible({
                    //     [pageButton.pageSave] : false,
                    //     [pageButton.pageEdit] : true
                    // });
                }
            });
        },
        [pageButton.linkVoucher]:() => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用主键再取一下外层,主要适配作业任务打开单据时联查凭证
            if(!paramurl.ar){
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            if(paramurl.ar){
                let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
                if (billdata.head.head.rows.length){
                    linkVoucherApi.link({
                        data  : {
                            props : props,
                            record : {
                                pk_billtype : billdata.head.head.rows[0].values.djlxbm.value,
                                pk_group : billdata.head.head.rows[0].values.pk_group.value,
                                pk_org : billdata.head.head.rows[0].values.pk_org.value,
                                relationID : billdata.head.head.rows[0].values.pk_jkbx.value
                            },
                            appid : paramurl.ar
                        }
                    })
                }else{
                    toast({ content: multiLang && multiLang.get('201102BCLF-0028'), color: 'danger' });
                }
            }
        },
        [pageButton.linkBudget]:() => {
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
            if (billdata.head.head.rows.length){
                linkBudgetApi.link({
                    data : {
                        "tradetype": billdata.head.head.rows[0].values.djlxbm.value,
                        "openbillid" : billdata.head.head.rows[0].values.pk_jkbx.value
                    },
                    success: (data) => {
                        this.setState({
                            sourceData: data,
                            showLinkBudget: true
                        })
                    }
                })
            }
        },
        [pageButton.billApprove]: () => {
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
            this.setState({
                ShowApproveDetail: true,
                billId: billdata.head.head.rows[0].values.pk_jkbx.value,
                billtype: billdata.head.head.rows[0].values.djlxbm.value
            });
        },
        //制单按钮逻辑
        [pageButton.pageMakebill]: () => {
            let pk_jkbx=props.form.getFormItemsValue("head","pk_jkbx").value;//表头的单据主键
            let djlxbm=props.form.getFormItemsValue("head","djlxbm").value;//单据类型编码
            let djdl=props.form.getFormItemsValue("head","djdl").value;//单据类型编码
            // let payflag=props.form.getFormItemsValue("head","payflag").value;//支付状态
            // let djzt=props.form.getFormItemsValue("head","djzt").value;//单据状态
            // let sxbz=props.form.getFormItemsValue("head","sxbz").value;//生效状态
            let pk_org=props.form.getFormItemsValue("head","pk_org").value;//机构
            //后台接口业务参数
            let makebillArr = {
                "pk_jkbx":pk_jkbx,
                "djlxbm":djlxbm,
                // "payflag":payflag,
                // "djzt":djzt,
                // "sxbz":sxbz,
                "pk_org":pk_org
            };
            console.log("制单按钮参数："+makebillArr);
            requestApi.makebill({
                data:makebillArr,
                success:(data)=>{
                console.log("后台制单逻辑响应参数"+data);
                let srccode = "erm" + data.cachekey;
                cacheTools.set("erm" + data.cachekey, data.pklist);
                //跳转
                props.openTo(data.url, {
                    status: 'edit',
                    appcode: data.appcode,
                    pagecode: data.pagecode,
                    pagekey:'',
                    ifshowQuery:true,
                    n: '凭证生成',//'凭证生成'
                    scene: srccode
                });

                },
                error:(data)=>{
                    toast({ content: data.message, color: 'danger' });
                }
            });

        },
        ["LinkQueryJsd"]: ()=>{
            let billdata =  props.createExtCardData(props.meta.getMeta().code, "head", bodyarr);
            requestApi.linkqueryjsd({
                data:billdata,
                success:(data) =>{
                    console.log(data);
                    props.openTo(data.data.ys.url,{"id":data.data.ys.id,"pagecode":data.data.ys.pagecode,"appcode":data.data.ys.appcode,"scene":data.data.ys.scene,"status":data.data.ys.status});
                    props.openTo(data.data.yf.url,{"id":data.data.yf.id,"pagecode":data.data.yf.pagecode,"appcode":data.data.yf.appcode,"scene":data.data.yf.scene,"status":data.data.yf.status});
                }
            });
        },

        ['pageWallet']: () => {
            console.log('enter invoice wallet modal')
            //传票夹列表查询参数
            let param = {};
            param.tradetype = window.presetVar.tradetype;
            param.pk_jkbx = props.form.getFormItemsValue("head","pk_jkbx").value;
            param.jkbxr = props.form.getFormItemsValue("head","jkbxr").value;
            param.pk_org = props.form.getFormItemsValue("head","pk_org").value;
            window.invoiceListQueryParam = param;
            this.setState({showInvoiceWallet: true})
        },

        // 本地上传
        ["local_invoice_btn"]: async() => {
            this.setState({showUploadInvoice: true})

        },

    }
}
export default pageButtonClick;
